package org.dinner.order.web;

import java.util.Map;

import javax.validation.Valid;

import org.dinner.order.model.User;
import org.dinner.order.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/user.add", method = RequestMethod.GET)
	public String createUser(Map<String, Object> map) {

		map.put("user", new User());

		return "user";
	}
	
	@RequestMapping(value = "/user.add", method = RequestMethod.POST)
	public String addContact(@Valid @ModelAttribute("user") User user,
			BindingResult result) {

		if (result.hasErrors()) {
			return "user";
		}
		user.setPassword(new Md5PasswordEncoder().encodePassword(user.getPassword(), null));
		
		userService.add(user);

		return "redirect:/";
	}

}
